<?php
namespace app\index\controller;
use think\Exception;

class Account extends Base {
    private $user;
    private $accountInfo;

    public function _initialize() {
        parent::_initialize();
        $this->user = $this->getLoginUser();
        if(!$this->user || !$this->user->id){
            $this->redirect(url('users/login'));
        }
        $this->accountInfo = model('Users')->find(['id' => $this->user->id]);
        $this->assign('user',$this->accountInfo);
    }

    public function index(){
        return $this->fetch();
    }

    public function edit(){
        //判断是否为post请求
        if(request()->isPost()){
            //处理用户资料修改逻辑
            $data = input('post.'); //获取表单数据
            try{
                model('Users')->updateData($data, $this->user->id);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('修改成功',url('account/index'));
        }else{
            return $this->fetch();
        }
    }

    public function cert(){
        //判断是否为post请求
        if(request()->isPost()){
            //实名资料入库逻辑
            $data = input('post.'); //获取表单数据
            try{
                $this->accountInfo->certDataInput($data, $this->user->id);
            } catch (Exception $e){
                $this->error($e->getMessage());
            }
            $message = "恭喜您，资料提交成功，请耐心等待后台管理员审核！<a href='". url('account/index') ."'>点击返回</a>";
            $this->assign('message',$message);
            $this->assign('title','实名认证');
            $this->assign('buttonDisplay',0);
            $this->assign('h1','验证');
            return $this->fetch('users/message');
        }else{

            if(!empty($this->accountInfo->userExtend->id)){
                if($this->accountInfo->userExtend->status == 0){
                    $message = "您的实名资料已提交，请耐心等待后台管理员审核！<a href='". url('account/index') ."'>点击返回</a>";
                    $this->assign('message',$message);
                    $this->assign('title','实名认证');
                    $this->assign('buttonDisplay',0);
                    $this->assign('h1','验证');
                    return $this->fetch('users/message');
                } else {
                    $message = "恭喜您，已经通过了实名认证了！<a href='". url('account/index') ."'>点击返回</a>";
                    $this->assign('message',$message);
                    $this->assign('title','实名认证');
                    $this->assign('buttonDisplay',0);
                    $this->assign('h1','验证');
                    return $this->fetch('users/message');
                }
            } else {
                $allCitys = model('City')->getAllCities();
                $this->assign('allCitys', $allCitys);
                return $this->fetch();
            }
        }
    }
}